package com.ylp.web.handler;

import com.ylp.beans.BeanFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @description:
 * @date: 2019/9/13 20:01.
 * @author: yulipeng.
 */
public class MappingHandler {

    /**
     * controller-方法名
     */
    private Method method;

    /**
     * controller-方法的url（格式例如：/getStudent）
     */
    private String uri;

    /**
     * controller类
     */
    private Class<?> controller;

    /**
     * controller-方法名中的-参数
     */
    private String[] args;

    public MappingHandler(String uri, Method method, Class<?> controller, String[] args) {
        this.uri = uri;
        this.method = method;
        this.controller = controller;
        this.args = args;
    }

    public boolean handle(ServletRequest req, ServletResponse resp) throws IllegalAccessException,
            InvocationTargetException, IOException {

        // 获取请求url;
        String reqUri = ((HttpServletRequest)req).getRequestURI();
        if (!uri.equals(reqUri)) {
            return false;
        }

        // 获取方法的参数；
        Object[] params = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            params[i] = req.getParameter(args[i]);
        }

        //Object ctl = controller.newInstance();
        Object ctl = BeanFactory.getBean(controller);
        Object response = method.invoke(ctl, params);

        System.out.println(response.toString());
        resp.getWriter().println(response.toString());
        return true;
    }
}
